package com.qf.student.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qf.student.bo.LoginBO;
import com.qf.student.common.Const;
import com.qf.student.dao.AdminMapper;
import com.qf.student.dao.StudentMapper;
import com.qf.student.dao.TeacherMapper;
import com.qf.student.entity.Student;
import com.qf.student.response.R;
import com.qf.student.service.ISystemService;
import com.qf.student.utils.TokenUtils;
import com.qf.student.vo.input.LoginInputVo;
import com.qf.student.vo.output.LoginOutputVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * @author YaoJiXing
 * created 2022/11/21 21:32
 */
@Service
public class SystemServiceImpl implements ISystemService {

    @Autowired
    private StudentMapper studentMapper;

    @Autowired
    private TeacherMapper teacherMapper;

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private LoginBO loginBO;

    @Override
    public R doLogin(LoginInputVo inputVo) {
        LoginOutputVo user = loginBO.getUserByUserName(inputVo);
        if (user != null && user.getPassword().equals(inputVo.getPassword())) {
            if (inputVo.getType() == Const.UserType.STUDENT) {
                studentMapper.updateById(new Student(user.getUserId(), LocalDateTime.now()));
            }
            return R.createSuccess("登录成功", TokenUtils.createJwtToken("user", user));
        }
        return R.createFAIL("用户名或者密码有误");
    }

    @Override
    public R getLastLoginTime(Integer userid) {
        Student student = studentMapper.selectOne(
                new QueryWrapper<Student>().eq("student_number", userid));
        Student lastTime = new Student();
        if (student != null) {
            lastTime.setStudentLastLoginTime(student.getStudentLastLoginTime());
        } else {
            lastTime.setStudentLastLoginTime(LocalDateTime.now());
        }
        return R.createSuccess(lastTime);

    }

}
